package com.shjn.squirrel.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.shjn.squirrel.R;
import com.shjn.squirrel.application.MyApplication;
import com.shjn.squirrel.bean.httpBean.RecordBean;
import com.shjn.squirrel.bean.httpBean.SaveRecyclingRecordReq;
import com.shjn.squirrel.customView.BackAndTimerView;
import com.shjn.squirrel.model.Constant;
import com.shjn.squirrel.model.LocalStorage;
import com.shjn.squirrel.model.RecyclerInfoCache;
import com.shjn.squirrel.utils.OkhttpHelper;
import com.shjn.squirrel.utils.OrderUtils;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 回收员关闭箱门
 */
public class RecyclerCloseFragment extends BaseFragment implements View.OnClickListener {

    private static RecyclerCloseFragment instance;
    private TextView mCategory;
    private TextView mQuantity;
    private TextView mPrice;
    private Button mRecyclerAgain;
    private Button mRecyclerBackIndex;
    private TextView mBalance;

    public RecyclerCloseFragment() {
    }

    public synchronized static RecyclerCloseFragment getInstance() {
        if (instance == null) {
            instance = new RecyclerCloseFragment();
        }
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return createView(inflater, R.layout.recycler_close_door, container);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initTimer();
        initView();
    }

    /**
     * 初始化倒计时器
     */
    private void initTimer() {
        mActivity.mBackAndTimer.setOnBackListener(null).setBackVisibleState(false)
                .setOnTimerFinishListener(new BackAndTimerView.OnTimerFinishListener() {
                    @Override
                    public void onTimerFinish() {
                        //返回首页
                        if (!UserSelectFragment.getInstance().isAdded()) {
                            recyclerLogout();
                        }
                    }
                }).setTime(60).setVisibleState(true).start();
    }

    /**
     * 初始化相关控件
     */
    private void initView() {
        mRecyclerAgain = (Button) mView.findViewById(R.id.btn_again_recycle);
        mRecyclerBackIndex = (Button) mView.findViewById(R.id.btn_back_index);
        mRecyclerAgain.setOnClickListener(this);
        mRecyclerBackIndex.setOnClickListener(this);
        mCategory = (TextView) mView.findViewById(R.id.tv_category);
        mQuantity = (TextView) mView.findViewById(R.id.tv_garbage_value);
        mPrice = (TextView) mView.findViewById(R.id.tv_price_value);
        mBalance = (TextView) mView.findViewById(R.id.tv_balance);

        mCategory.setText(RecyclerInfoCache.garbageParam.getCategory() + "回收物");
        if (RecyclerInfoCache.garbageParam.getCategory().equals(Constant.bottle)) {
            mQuantity.setText(String.format("%.0f", RecyclerInfoCache.garbageParam.getQuantity()) + "个");
        } else {
            mQuantity.setText(String.format("%.2f", RecyclerInfoCache.garbageParam.getQuantity()) + "公斤");
        }
        mPrice.setText(String.format("%.2f", RecyclerInfoCache.garbageParam.getMoney()) + "元");

        mBalance.setText(String.format("%.2f", RecyclerInfoCache.balance) + "元");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_again_recycle:
                //继续取货
                if (!RecyclerSelectFragment.getInstance().isAdded()) {
                    mActivity.mBackAndTimer.stop();
                    mActivity.getFragmentManager().beginTransaction()
                            .replace(R.id.mid, RecyclerSelectFragment.getInstance())
                            .commit();
                }
                break;
            case R.id.btn_back_index:
                //返回首页
                if (!UserSelectFragment.getInstance().isAdded()) {
                    recyclerLogout();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 回收员退出登录
     */
    private void recyclerLogout() {
        //暂停倒计时器
        mActivity.mBackAndTimer.setVisibleState(false).stop();
        //上传回收记录
        final ArrayList<RecordBean> records = new ArrayList<>();
        for (String key : RecyclerInfoCache.records.keySet()) {
            if (key.equals(Constant.bottle)) {
                records.add(new RecordBean(Constant.categoryMap.get(key)[3], RecyclerInfoCache.records.get(key).intValue(), 0));
            } else {
                records.add(new RecordBean(Constant.categoryMap.get(key)[3], 0, RecyclerInfoCache.records.get(key)));
            }
        }
        String account = RecyclerInfoCache.telNum;
        Log.i("info", "recyclerSaveRecord_request: " + new Gson().toJson(new SaveRecyclingRecordReq(LocalStorage.getDeviceID(MyApplication.getInstance()),
                account, OrderUtils.getSerialNumber(), records)));
        //----------测试用-------------//
//        OkhttpHelper.postRequest(Constant.baseUrl + "machine/recycling/saveRecord",
//                new Gson().toJson(new SaveRecyclingRecordReq(LocalStorage.getDeviceID(MyApplication.getInstance()),
//                        account, OrderUtils.getSerialNumber(), records)),
//                new Callback() {
//                    @Override
//                    public void onFailure(Call call, IOException e) {
//                        Log.i("info", "recyclerSaveRecord_onFailure: " + e.getMessage());
//                    }
//
//                    @Override
//                    public void onResponse(Call call, Response response) throws IOException {
//                        Log.i("info", "recyclerSaveRecord_response:" + response.body().string());
//                    }
//                });
        //清空记录
        RecyclerInfoCache.clearRecyclerInfo();
        //跳转到首页
        mActivity.getFragmentManager().beginTransaction()
                .replace(R.id.mid, UserSelectFragment.getInstance())
                .commit();
        TopFragment.getInstance().mBtnMyRecycler.setVisibility(View.VISIBLE);
    }
}
